#! /usr/bin
#-*- coding:utf-8 -*-


__author__ = 'Michael'

import time
import pymongo
import os
from log import log
from post import *
from config import *
import airspeed

class post_entry:
    def __init__(self):
        self.__log = log("hblog")
        pass

    def run(self, title, src, tags, categories):
        """
        save src&refined content
        """
        
        conn = pymongo.Connection()
        db = conn.hblog

        id = db.post.find().count()

        self.__log.debug("generate post id: %s" % id)

        p = post(self.__log, title, src, tags, categories)
        t = time.gmtime()
        
        title = p.getTitle()
        seo_title = p.getSeoTitle()
        r_src = p.getContent()
        tags = p.getTags()
        categories = p.getCategory()

        self.__log.debug("generate seo_title: %s" % seo_title)

        s_path = self.__generateStaticFile(t, title, seo_title, r_src, tags, categories)

        self.__log.debug("build static path: %s" % s_path)

        p = {"id":id,
             "title": title,
             "seo_title": seo_title,
             "src": src,
             "tags": tags,
             "category": categories,
             "time": time.ctime(time.mktime(t)),
             "s_path": s_path
        }

        db.post.save(p)
        conn.disconnect()
        

    def __generateStaticFile(self, t, title, seo_title, r_src, tags, cats):
        dir = "%s/%s/%s/%s" % (config.getStaticRoot(), t.tm_year, t.tm_mon, t.tm_mday)
        s_path = "./%s/%s.html" % (dir, seo_title)

        file = open(config.getTemplateForBlock("post"), "r")
        template = file.read()
        file.close()

        self.__log.debug("template: %s" % template)
        output = airspeed.Template(template).merge({"title": title,
                                                    "time": time.ctime(time.mktime(t)),
                                                    "r_src": r_src,
                                                    "category": '/'.join(cats),
                                                    "tags": ','.join(tags)
                                                    })
        self.__log.debug("template merge output: %s" % output)

        if not os.path.isdir(dir):
            os.makedirs(dir)

        o = open(s_path, "w")
        o.write(output)
        o.close()

        return s_path



    

if __name__ == "__main__":

    title = "i'm title"
    src = """
*escape() method*

Defined in: JavaScript 1.0
* Descriptions 汉字

    """
    tags  = "michael,sanni"
    categories = "design/ue"
        
    pe = post_entry()
    pe.run(title, src, tags, categories)
